
const KEY_NODE_DATA = 'nodeData';

function saveNodeDataToLocalStorage(data) {
  // TODO: 缓存，可以考虑存到服务端，草稿状态
  localStorage.setItem(KEY_NODE_DATA, JSON.stringify(data));
}

export default {
  namespace: 'editor',
  state: {
    nodeData: JSON.parse(localStorage.getItem(KEY_NODE_DATA) || '[]'),
    currNode: null,
    scale: 1,
  },
  effects: {
    *setScale({ payload }, { put, select }) {
      yield put({
        type: 'saveState',
        payload: {
          scale: payload,
        },
      });
      return payload;
    },
    *addNodeData({ payload }, { put, select }) {
      let nodeData = yield select(state => state.editor.nodeData);
      let newNodeData = [...nodeData, payload];
      saveNodeDataToLocalStorage(newNodeData);
      yield put({
        type: 'saveState',
        payload: {
          nodeData: newNodeData,
          currNode: payload,
        },
      });
      return newNodeData;
    },
    *modNodeData({ payload }, { put, select }) {
      const { id } = payload;
      let nodeData = yield select(state => state.editor.nodeData);
      const newNodeData = nodeData.map(item => {
        if (item.id === id) {
          return payload;
        }
        return { ...item };
      });
      saveNodeDataToLocalStorage(newNodeData);
      yield put({
        type: 'saveState',
        payload: {
          nodeData: newNodeData,
          currNode: payload,
        },
      });
      return newNodeData;
    },
    *delNodeData({ payload }, { put, select }) {
      const { id } = payload;
      let nodeData = yield select(state => state.editor.nodeData);
      const newNodeData = nodeData.filter(item => item.id !== id);
      saveNodeDataToLocalStorage(newNodeData);
      yield put({
        type: 'saveState',
        payload: {
          nodeData: newNodeData,
          currNode: null,
        },
      });
      return newNodeData;
    },
  },
  reducers: {
    saveState(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
  },
  subscriptions: {
    setup({ dispatch, history }) {
      return history.listen(({ pathname, query }) => { });
    },
  },
};
